class Video < ActiveRecord::Base

  URL_PATH = "http://192.168.1.100/converted"
  CONVERTED_PATH = "/data"
  IPHONE_UPLOADS = "/home/essl/iphone/var/root/Downloads"
  VIDEOS_PATH = "/data/Incoming/Completed/"
  EXTENTIONS = "avi,mpeg,mkv,m4v,mpg,wmv"
  EXCLUDE = "ndsu"

  def Video::update_files
    files = Dir.glob(File.join("#{VIDEOS_PATH}/**", "*.{#{EXTENTIONS}}"))
    files.reject!{|f| f =~ /#{EXCLUDE}/}
    new_files = files - Video.find(:all).collect(& :path)
    dead_files = Video.find(:all).collect(& :path) - files
    dead_files.each do |f|
      v = Video.find_by_path(f)
      v.destroy
    end
    new_files.each do |f|
      Video.create :name => f.gsub(/#{VIDEOS_PATH}/, ""), :path => f
    end
  end

  def transcode
    self.status = 'progress'
    save
    begin
      Dir.mkdir(CONVERTED_PATH)
    rescue
      nil
    end
    new_name = "#{id}.mp4"
    system ("nice ffmpeg -i #{path} -r 20 -vb 256 -ab 96 -s qvga -sameq -y '#{CONVERTED_PATH}/#{new_name}'")
    self.converted_name = "#{id}.m4v"
    system("mv '#{CONVERTED_PATH}/#{new_name}' '#{local_path}'") 
    self.status = 'converted'
    save
  end

  def delete
    begin
      File.delete(local_path)
    rescue
      nil
    end
    reset
  end

  def download
    system("cd #{IPHONE_UPLOADS}; mkdir #{relative_path}")
    system("cp '#{local_path}' '#{IPHONE_UPLOADS}/#{name}.mp4'")
    return true
  end

  def Video.check_iphone
    if !system("touch '#{IPHONE_UPLOADS}/testing.tmp'")
      return false
    end
    system("rm '#{IPHONE_UPLOADS}/testing.tmp' -f")
    return true
  end

  def reset
    self.status = 'none'
    self.converted_name = nil
    save
  end

  def converted
    self.status = 'converted'
    save
  end

  def started?
    status != 'none'
  end

  def ready?
    status == 'converted'
  end

  def local_path
    "#{CONVERTED_PATH}/#{converted_name}"
  end

  def relative_path
    m = name.match(/^\/(.*)\/.*$/)
    unless m.nil?
      return m[1]
    else
      return "/"
    end
  end

  def url
    "#{URL_PATH}/#{converted_name}"
  end

  def <=> (other)
    name <=> other.name
  end

  def before_destroy
    delete
  end
end
